//
//  MainViewModel.swift
//  GoldStar
//
//  Created by TRS-Mobile on 2025/6/24.
//

import Foundation
import RxCocoa
import RxSwift
import SwiftyUserDefaults

class MainViewModel: ViewModelType {
    
    struct Input {
        let userName: Observable<String>
        let deleteTrigger: Observable<Bool>
    }
    
    struct Output {
        let users: BehaviorRelay<[UserViewModel]>
    }
    
    private let disposeBag = DisposeBag()
    
    func transform(input: Input) -> Output {
        let users: BehaviorRelay<[UserViewModel]> = BehaviorRelay(value: loadLocalUsers())
        input.userName
            .filter {!$0.isEmpty}
            .map { UserModel(name: $0) }
            .subscribe {[weak self] in
                self?.saveUser($0)
                users.accept(users.value + [.init(user: $0)])
            }
            .disposed(by: disposeBag)
        
        input.deleteTrigger
            .filter { $0 }
            .subscribe { _ in
                Defaults.removeAll()
                users.accept([])
            }
            .disposed(by: disposeBag)
        
        return Output(users: users)
    }
    
    func saveUser(_ user: UserModel) -> Void {
        Defaults.localUsers.append(user)
    }
    
    func loadLocalUsers() -> [UserViewModel] {
        return Defaults.localUsers
            .map { UserViewModel(user: $0) }
    }
    
}
